<template>
  <div class="app-container">
    <el-card style="position: relative">
      <RouterHeader :title="title()"></RouterHeader>

      <el-form
        :model="form"
        :rules="rules"
        ref="ruleFormRef"
        label-width="140px"
        label-position="right"
      >
        <el-row :gutter="20" class="form-single-info">
          <el-col :span="20">
            <div class="title"><h5>基本信息</h5></div>

            <el-row>
              <el-col :span="12">
                <el-form-item label="项目名称" prop="planName">
                  <el-input
                    class="input-item"
                    v-model="form.planName"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="项目编号">
                  <el-input
                    class="input-item"
                    v-model="form.planEncode"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="业务类型" prop="businessTypeList">
                  <el-cascader
                    v-model="form.businessTypeList"
                    ref="ref_business"
                    :options="businesstypeTree"
                    :props="businesstProps"
                    :show-all-levels="true"
                    clearable
                    @change="businessChange"
                    :disabled="isDisabled()"
                  ></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业主单位" prop="enterpriseName">
                  <el-input
                    class="input-item"
                    v-model="form.enterpriseName"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目联系人" prop="enterpriseContact">
                  <el-input
                    class="input-item"
                    v-model="form.enterpriseContact"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目联系人电话" prop="contactPhone">
                  <el-input
                    class="input-item"
                    v-model="form.contactPhone"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预计合同金额" prop="expectedContractMoney">
                  <el-input
                    type="number"
                    class="input-item"
                    v-model="form.expectedContractMoney"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  >
                    <template #append>
                      <el-select
                        v-model="form.units"
                        placeholder="请选择"
                        style="width: 115px"
                      >
                        <el-option
                          v-for="item in unitsList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.label"
                        >
                        </el-option>
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目总投资额">
                  <el-input
                    type="number"
                    class="input-item"
                    v-model="form.investment"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  >
                    <template #append> 万元 </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="预计成交日期" prop="expectedDealDate">
                  <el-date-picker
                    v-model="form.expectedDealDate"
                    type="datetime"
                    placeholder="选择日期"
                    style="width: 100%"
                    :disabled="isDisabled()"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  ></el-date-picker>
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="所在地区" prop="addressList">
                  <el-cascader
                    v-model="form.addressList"
                    ref="ref_areaCodes"
                    :options="areaCodelist"
                    :props="areaCodeprops"
                    :show-all-levels="true"
                    clearable
                    :disabled="isDisabled()"
                    @change="handleChange"
                  ></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="行业" prop="industrys">
                  <el-select
                    v-model="form.industrys"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审批部门">
                  <el-select
                    v-model="form.approvaDepts"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  >
                    <el-option
                      v-for="item in approvalDeptOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="监督部门">
                  <el-select
                    class="input-item"
                    v-model="form.superviseDepts"
                    placeholder="请选择"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    :disabled="isDisabled()"
                  >
                    <el-option
                      v-for="item in superviseDeptOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同工期" prop="contractDuration">
                  <el-date-picker
                    v-model="datetime"
                    type="daterange"
                    range-separator="To"
                    start-placeholder="请选择"
                    end-placeholder="请选择"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :disabled="isDisabled()"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="投标项目" prop="tenderProject">
                  <el-radio-group
                    v-model="form.tenderProject"
                    :disabled="isDisabled()"
                  >
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="上传进度计划表" prop="planscFileList">
                  <fileupload v-if="String(ist) == '3'" 
                    @update:modelValue="handleplanscFile"
                    :modelValue="form.planscFileList"
                    :flag="route.query.name === '6' ? true : false">
                  </fileupload>

                  <indexcategory v-else-if="String(ist) == '1'"
                    @update:modelValue="handleplanscFile"
                    :modelValue="form.planscFileList"
                    :flag="route.query.name === '6' ? true : false" >
                  </indexcategory>
                  <indexcategorysecond v-else-if="String(ist) == '2'" 
                    @update:modelValue="handleplanscFile"
                    :modelValue="form.planscFileList"
                    :flag="route.query.name === '6' ? true : false" >
                  </indexcategorysecond>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目简述" prop="projectBriefly">
                  <!-- maxlength="150" -->
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.projectBriefly"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目备注" prop="projectRemark">
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.projectRemark"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="上传附件/图片" prop="projectFileList">
                  <fileupload v-if="ist == '3'" 
                    :modelValue="form.projectFileList"
                    @update:modelValue="handleModelValueFiles"
                    :flag="route.query.name === '6' ? true : false">
                  </fileupload>

                  <indexcategory v-if="ist == '1'" 
                    :modelValue="form.projectFileList"
                    @update:modelValue="handleModelValueFiles"
                    :flag="route.query.name === '6' ? true : false">
                  </indexcategory>

                  <indexcategorysecond v-if="ist == '2'" 
                    :modelValue="form.projectFileList"
                    @update:modelValue="handleModelValueFiles"
                    :flag="route.query.name === '6' ? true : false">
                  </indexcategorysecond>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="title">
              <h5>项目成员</h5>
              <selectPeople
                ref="childRef"
                :projectUserDtoList="form.projectUserDtoList"
                @conversionRole="conversionRole"
                @selectTable="selectTable"
                @deleteTable="deleteTable"
                @handelChange="handelChange"
              ></selectPeople>
            </div>
            <div class="table_container">
              <el-table
                :data="form.projectUserDtoList"
                style="width: 100%"
                header-cell-class-name="table-header-gray"
              >
                <el-table-column
                  type="index"
                  align="center"
                  width="55"
                  label="序号"
                ></el-table-column>
                <el-table-column prop="nickName" align="center" label="姓名">
                  <template #default="scope">
                    {{ scope.row.nickName }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="phonenumber"
                  align="center"
                  label="手机号"
                ></el-table-column>
                <el-table-column
                  prop="projectRole"
                  align="center"
                  label="项目角色"
                >
                  <!-- v-if="route.query.name === '1'" -->
                  <template #default="scope">
                    {{ getRoleLabel(scope.row.projectRole) }}
                  </template>
                  <!-- <template
                    #default="scope"
                    v-else-if="route.query.name !== '1'"
                  >
                    {{ scope.row.projectRole }}
                  </template> -->
                </el-table-column>
                <el-table-column
                  prop="dept.deptName"
                  align="center"
                  label="部门"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  align="center"
                  label="岗位"
                  show-overflow-tooltip
                >
                  <template #default="scope" v-if="route.query.name === '1'">
                    {{ scope.row.postName }}
                  </template>
                  <template
                    #default="scope"
                    v-else-if="route.query.name !== '1'"
                  >
                    <div v-for="(post, index) in scope.row.posts" :key="index">
                      {{ post.postName }}
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  align="center"
                  label="操作"
                  v-if="route.query.name === '1' || route.query.name === '2'"
                >
                  <template #default="scope">
                    <!-- <div @click="tableDelect(scope.row)">删除</div> -->
                    <el-tag
                      v-if="userStore.userId !== scope.row.userId"
                      @click="tableDelect(scope.$index, scope.row)"
                      style="cursor: pointer"
                      >删除</el-tag
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div v-if="route.query.name !== '1'">
              <div class="title"><h5>项目审批进度</h5></div>
              <el-timeline style="max-width: 600px">
                <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :color="activity.color"
                  :timestamp="activity.updateTime"
                >
                  <div style="display: flex; align-items: center">
                    <img :src="url + activity.avatar" class="user-avatar" />
                    <span
                      style="
                        font-size: 14px;
                        font-weight: 500;
                        margin-left: 5px;
                      "
                    >
                      {{ activity.username }} ({{
                        activity.checkHisResult === "2" ? "未审核" : "已审核"
                      }})
                      {{
                        activity.zuofei === "0"
                          ? " _作废"
                          : activity.zuofei === "null"
                          ? ""
                          : ""
                      }}
                      :
                    </span>

                    <span
                      style="
                        font-size: 14px;
                        font-weight: 400;
                        margin-left: 5px;
                      "
                    >
                      {{ activity.opinion }}</span
                    >
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>

            <!-- 详情的时候 不展示 -->
            <div
              v-if="
                route.query.name === '1' ||
                route.query.name === '2' ||
                route.query.name === '6'
              "
            >
              <div class="title">
                <h5>项目审批流程</h5>
              </div>
            </div>

            <el-row
              v-if="
                route.query.name === '1' ||
                route.query.name === '2' ||
                route.query.name === '6'
              "
            >

              <el-col :span="24">
                <el-form-item label="审批方式">
                  <el-radio-group
                    v-model="processCheckBo.checkType"
                    :disabled="isDisabled()"
                  >
                    <el-radio :label="0">自由审批</el-radio>
                    <el-radio :label="1">逐级审批</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item
                  label="审批流程"
                  style="padding: 20px 0"
                  v-if="
                    (route.query.name === '6' &&
                      processCheckBo.checkType === 0 &&
                      form.keepCheck === '1') ||
                    (route.query.name !== '6' && form.keepCheck === '1')
                  "
                >
                  <approver
                    :approverList="processCheckBo.checkPeopleIds"
                    :typeId="3"
                    :isEdit="!!$route.query.projectId"
                    @handleChooseapprover="handleChooseapprover"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item
                  label="抄送"
                  style="padding: 20px 0"
                  v-if="
                    (route.query.name === '6' &&
                      processCheckBo.checkType === 0 &&
                      form.keepCheck === '1') ||
                    (route.query.name !== '6' && form.keepCheck === '1')
                  "
                >
                  <approver
                    :typeId="3"
                    :approverList="processCheckBo.copyFor"
                    :isCc="true"
                    @handleChooseapprover="handleChooseapproverCc"
                  ></approver>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="route.query.name === '6' || route.query.name === '5'">
              <el-col :span="24">
                <el-form-item label="审批意见" prop="projectImplementation">
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    maxlength="150"
                    show-word-limit
                    v-model="form.approvalOpinions"
                    placeholder="请输入"
                    :disabled="route.query.name === '5' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="添加附件/图片"
                  prop="projectImplementation"
                >
                  <fileupload
                    :modelValue="form.approvalFile"
                    @update:modelValue="handleModelFileLists"
                  >
                  </fileupload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="审批决定"
                  prop="projectImplementation"
                  v-if="processCheckBo.checkType !== 1"
                >
                  <el-radio-group
                    v-model="form.keepCheck"
                    class="ml-4"
                    :disabled="route.query.name === '5' ? true : false"
                  >
                    <el-radio label="0" size="large">完成审批</el-radio>
                    <el-radio label="1" size="large">继续审批</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <div
          v-if="hasButtonSave"
          style="display: flex; justify-content: center"
        >
          <el-button @click="resetForm(ruleFormRef)">{{
            route.query.name === "6" ? "驳回" : "取消"
          }}</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">{{
            route.query.name === "6" ? "通过" : "提交"
          }}</el-button>
        </div>
      </el-form>
    </el-card>
    <!-- 选择人员 -->
  </div>
</template>

<script setup>
import RouterHeader from "@/components/RouterHeader";
import selectPeople from "@/components/selector/selectPeople.vue";
import approver from "@/components/Approve/approver.vue";
import fileupload from "@/components/FileUpload/index";
import indexcategory from "@/components/FileUpload/indexcategory";
import indexcategorysecond from "@/components/FileUpload/indexcategorysecond";
import {
  location,
  businessTypeList,
  addconversionApi,
  conversionDetailsList,
  updateApi,
  industryApi,
  getbusinessTypeDic
} from "@/api/project/conversion";
import { onMounted, nextTick, watchEffect } from "vue";

import { useRouter, useRoute } from "vue-router";
//@ts-ignore
import { useEmpty, dateChange } from "@/utils/index";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  approvalProcessApi,
  informationApprove,
  approvalTransfer,
} from "@/api/approvalManagement/approvaType.js";
import { approvalQueryApi } from "@/api/project/approval";
import useUserStore from "@/store/modules/user";
let url = import.meta.env.VITE_APP_BASE_API;

const radio1 = ref("2");

const fileList = ref([]); // 初始化文件列表

const options = ref([]);

const handelIndustry = async () => {
  const res = await industryApi();
  // console.log(res);
  if (res.code === 200 && res.data) {
    options.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

const datetime = ref();
// 开始时间
const createContract = ref();
// 结束时间
const endContract = ref();

const handleChange = (value) => {
  console.log(value);
};

let roleList = [
  {
    id: "1",
    label: "主管领导",
  },
  {
    id: "2",
    label: "项目经理",
  },
  {
    id: "3",
    label: "项目助理",
  },
];

// 审批部门option
const approvalDeptOptions = ref([
  {
    id: "1",
    label: "生态环境局",
  },
  {
    id: "2",
    label: "行政审批局",
  },
  {
    id: "3",
    label: "经济发展局",
  },
  {
    id: "4",
    label: "发展改革局",
  },
  {
    id: "5",
    label: "其他",
  },
]);

// 监督部门option
const superviseDeptOptions = ref([
  {
    id: "1",
    label: "住建",
  },
  {
    id: "2",
    label: "采购办",
  },
  {
    id: "3",
    label: "水利",
  },
  {
    id: "4",
    label: "交通",
  },
  {
    id: "5",
    label: "发改",
  },
  {
    id: "6",
    label: "环保",
  },
  {
    id: "7",
    label: "其他",
  },
]);

const unitsList = [
  { value: "0", label: "元" },
  { value: "1", label: "万元" },
  { value: "2", label: "亿元" },
];

const activities = ref([]);
// {
//   content: "Event start",
//   timestamp: "2018-04-15",
// },
// {
//   content: "Approved",
//   timestamp: "2018-04-13",
// },
// {
//   content: "Success",
//   timestamp: "2018-04-11",
// },

const getRoleLabel = (value) => {
  let matchedOption = roleList.find((option) => option.id === value);

  return matchedOption ? matchedOption.label : "";
};

const router = useRouter();
const title = () => {
  if (route.query.name === "1") {
    return "新建项目信息";
  } else if (route.query.name === "2") {
    return "编辑项目信息";
  } else if (route.query.name === "3" && route.query.showDetails) {
    return "详情项目信息";
  } else if (route.query.name === "3" && route.query.show) {
    return "详情转立项";
  } else if (route.query.name === "6" && route.query.show === "1") {
    return "转立项审批";
  } else {
    return "项目信息审批";
  }
};

const handelChange = (row) => {
  if (form.projectUserDtoList && form.projectUserDtoList[0]) {
    form.projectUserDtoList[0].projectRole = row.projectRole;
  }
};

const childRef = ref(null);

const route = useRoute();
// const detailsvisible = ref(false);

const form = reactive({
  planName: "", //项目名称
  businessTypeList: "", //业务类型
  enterpriseName: "", //业主单位
  enterpriseContact: "", //项目联系人
  contactPhone: "", //项目联系人电话
  expectedContractMoney: "", // 预计合同金额
  expectedDealDate: "", // 预计成交日期
  addressList: [], //所在地区
  industry: "", //行业
  industrys: "", //行业2
  tenderProject: 0, //投标项目
  secrecyAgreement: 0, //保密协议
  secrecyFileList: [], //上传保密协议
  projectBriefly: "", //项目简述
  projectRemark: "", //项目备注
  projectFileList: [], //上传附件
  projectUserDtoList: [], // 项目成员列表
  approvaDepts: [], // 审批部门
  superviseDepts: [], // 监督部门
  units: "",
  approvalOpinions: "", // 审批意见
  processCheckHistoryId: "",
  planEncode: "", //项目编号
  investment: "", //项目总投资额
  approvalFile: [],
  planscFileList: [],
  keepCheck: "1", //审批决定-完成审批
});
//
const processCheckBo = reactive({
  checkPeopleIds: [], //审核人id列表
  copyFor: [], //抄送人id列表
  checkType: 1, //逐级审批
});

const limit = 1;
const userStore = useUserStore();

const input3 = ref("");
const select = ref("");

const industryList = ref("");

const ruleFormRef = ref();

const areaCodelist = ref([]);

const scanningCopy = ref(null);

let checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入项目联系人电话"));
  } else if (!/^(\d{1,4})-(\d{6,8})$/.test(value) && !/^1\d{10}$/.test(value)) {
    callback(new Error("项目联系人电话格式不正确"));
  } else {
    callback();
  }
};

const rules = reactive({
  planName: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
  // planEncode: [{ required: true, message: "请输入项目编号", trigger: "blur" }],

  businessTypeList: [
    { required: true, message: "请选择业务类型", trigger: "change" },
  ],
  enterpriseName: [
    { required: true, message: "请输入业主单位", trigger: "blur" },
  ],
  enterpriseContact: [
    { required: true, message: "请输入项目联系人", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入项目联系人电话", trigger: "blur" },
    { validator: checkPhone, trigger: "blur" },
  ],
  addressList: [
    { required: true, message: "请选择所在地区", trigger: "change" },
  ],
  industry: [{ required: true, message: "请输入行业", trigger: "blur" }],
  tenderProject: [
    { required: true, message: "请选择是否为投标项目", trigger: "change" },
  ],
  secrecyFileList: [
    { required: true, message: "请选择是否上传保密协议", trigger: "change" },
  ],
});

const businesstProps = {
  value: "id",
  label: "businessName",
  checkStrictly: true,
  multiple: true,
  children: "children",
  // checkStrictly:true,
};

const areaCodeprops = {
  value: "id",
  label: "name",
  // checkStrictly: true,
  children: "rcDistrictList",
  multiple: true
};

const businesstypeTree = ref([]);


const showFileUpload=(e)=>{
  //类型1为'a-j',类型2为'册'
  //返回值示例：
  // [
  //   {
  //       "type": "6,89",
  //       "value": 1
  //   },
  //   {
  //       "type": "[6,88],[6,90]",
  //       "value": 2
  //   }
  // ]

  //先判断类型1，再判断类型2，其它为3
  let typedic1 = businessTypeDicData.filter(o=>{ if(o.value == 1) return o } );
  let typedic2 = businessTypeDicData.filter(o=>{ if(o.value == 2) return o } );
  let result = '3';
  //进行业务类型的判断
  if(e.length == 0){
    return result;
  }
  e.forEach(function(item){
    typedic1.filter(function(o){
      let typearr = JSON.parse("["+ o.type +"]");
      typearr.forEach(function(p){
        if(p.length == 2 
        && p.length == item.length 
        && p[0] == item[0]
        && p[1] == item[1]){
          result = typedic1[0].value;
        }
        else if(p.length == 1 
        && p.length == item.length 
        && p[0] == item[0]){
          result = typedic1[0].value;
        }
      });
    });
  });

  if(result == '1'){
    return result;
  }
  e.forEach(function(item){
    typedic2.filter(function(o){
      let typearr = JSON.parse("["+ o.type +"]");
      typearr.forEach(function(p){
        if(p.length == 2 
        && p.length == item.length 
        && p[0] == item[0]
        && p[1] == item[1]){
          result = typedic2[0].value;
        }
        else if(p.length == 1 
        && p.length == item.length 
        && p[0] == item[0]){
          result = typedic2[0].value;
        }
      });
    });
  });

  return result;
}

// 改变业务类型
const ist = ref('3');
const businessChange = (e) => {
  ist.value = showFileUpload(e);
};

// 业务类型下拉选项
const businessTypeOptions = async () => {
  let params = {};
  const response = await businessTypeList(params);
  if (response.code === 200 && response.data.length >= 0) {
    businesstypeTree.value = response.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 成功调取上传文件接口 上传保密协议
const handleplanscFile = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      //form.planscFileList.push(result);
      form.planscFileList = [];
      result.forEach((item)=>{
        form.planscFileList.push(item);
      });
    }
  } else if (operationType === "delete") {
    form.planscFileList.splice(result, 1);
  }
};

// 上传附件
const handleModelValueFiles = (val, result, operationType) => {
  // console.log(val, result, operationType);
  console.log(form.planscFileList);
  if (operationType === "success") {
    if (result) {
      form.projectFileList = [];
      result.forEach((item)=>{
        form.projectFileList.push(item);
      });
    }
  } else if (operationType === "delete") {
    form.projectFileList.splice(result, 1);
  }
};

// 审批附件
const handleModelFileLists = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      form.approvalFile = [];
      result.forEach((item)=>{
        form.approvalFile.push(item);
      });
    }
  } else if (operationType === "delete") {
    form.approvalFile.splice(result, 1);
  }
};

// 点击选择之后
const selectTable = (listVal) => {
  if (listVal) {
    form.projectUserDtoList.push(listVal);
  }
};

let optionsRole;

// 点击取消之后
const deleteTable = (val, index1) => {
  if (val) {
    form.projectUserDtoList.forEach((item, indexs) => {
      if (item.userId === val.userId) {
        form.projectUserDtoList.splice(indexs, 1);
      }
    });
  }
};

// 删除
const tableDelect = (index, val) => {
  form.projectUserDtoList.splice(index, 1);
};

const handelLocation = async () => {
  try {
    let params = {};
    const response = await location(params);
    if (response.code === 200 && response.data.length >= 0) {
      areaCodelist.value = response.data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 所在地区改变事件
// const areaCodesChange = () => {};

// const  approverId=ref([])

// 审批人
const handleChooseapprover = (id) => {
  if (id) {
    processCheckBo.checkPeopleIds = id;
  }
};

// 抄送人
const handleChooseapproverCc = (id) => {
  if (id) {
    processCheckBo.copyFor = id;
  }
};

const hasButtonSave = ref(false);

// 1.按钮保存隐藏
const hasButton = () => {
  if (route.query.name === "3" || route.query.name === "5") {
    hasButtonSave.value = false;
  } else {
    hasButtonSave.value = true;
  }
};

const disabled = ref(true);
// 2.控制表单项是否只读
const isDisabled = () => {
  if (
    route.query.name === "3" ||
    route.query.name === "6" ||
    route.query.name === "5"
  ) {
    return (disabled.value = true);
  } else {
    return (disabled.value = false);
  }
};

let approval = ref();

// 项目转化详情
const detailList = async () => {
  let id = route.query.planId || route.query.id;
  const response = await conversionDetailsList(id);
  // console.log(response);
  // 初始化赋值
  if (response.code === 200 && response.data) {
    for (let key in form) {
      if (response.data[key]) {
        form[key] = response.data[key];
      }
    }


    // 转化为数字类型
    form.tenderProject = Number(response.data.tenderProject);
    form.secrecyAgreement = Number(response.data.secrecyAgreement);

    // 转换成数组
    form.addressList = JSON.parse(response.data.address);
    
    //通过判断业务类型的，来显示上传文件框
    form.businessTypeList = response.data.test;
    ist.value = showFileUpload(response.data.test);

    // 文件转换
    form.secrecyFileList = response.data.secrecyFileList;
    form.projectFileList = response.data.projectFileList;
    datetime.value = [response.data.createContract, response.data.endContract];

    // 审批流程-审批
    // form.processCheckBo.checkPeopleIds = response.data.dataCheckInfo.checkList;

    // 审批人-抄送
    // form.processCheckBo.copyFor = response.data.dataCheckInfo.copyForList;

    // 审批进度列表
    activities.value = response.data.dataCheckInfo.opinons;
    //  审批id
    form.processCheckHistoryId =
      response.data.dataCheckInfo.processCheckHistoryId;

    // 行业
    form.industrys = JSON.parse(response.data.industry);
    form.approvaDepts = JSON.parse(response.data.approvalDept);
    form.superviseDepts = JSON.parse(response.data.superviseDept);
    
    // 审批方式
    processCheckBo.checkType =
      response.data &&
      response.data.dataCheckInfo &&
      response.data.dataCheckInfo.checkType;


    approval.value =
      response.data &&
      response.data.dataCheckInfo &&
      response.data.dataCheckInfo.checkType;

    if (route.query.name === "5") {
      // 审批意见
      form.approvalOpinions =
        response.data &&
        response.data.dataCheckInfo &&
        response.data.dataCheckInfo.myCheckOpinionBo &&
        response.data.dataCheckInfo.myCheckOpinionBo.opinion;
      // 审批附件
      form.approvalFile =
        response.data &&
        response.data.dataCheckInfo &&
        response.data.dataCheckInfo.myCheckOpinionBo &&
        response.data.dataCheckInfo.myCheckOpinionBo.fileList;
      // 审批决定
      form.keepCheck =
        response.data &&
        response.data.dataCheckInfo &&
        response.data.dataCheckInfo.myCheckOpinionBo &&
        response.data.dataCheckInfo.myCheckOpinionBo.keepCheck;
    }
  }
};

// 提交
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (datetime.value && datetime.value[0]) {
        createContract.value = datetime.value[0];
      }
      if (datetime.value && datetime.value[1]) {
        endContract.value = datetime.value[1];
      }
      // 新增
      if (route.query.name === "1") {
        let newArray = [];
        let userCcIds;
        let userIds;
        let requestPayload;
        if (processCheckBo.copyFor) {
          userCcIds = processCheckBo.copyFor.map((item) =>
            item.userId ? Number(item?.userId) : item
          );
        }

        if (processCheckBo.checkType === 1) {
          // 逐级审批 orderCheckPeopleInfoList
          // 使用 map 方法重构数组
          newArray = processCheckBo.checkPeopleIds.map((item, index) => {
            return {
              orderNum: index + 1,
              userId: item.userId ? Number(item?.userId) : item,
            };
          });
          requestPayload = {
            ...form,
            createContract: createContract.value,
            endContract: endContract.value,
            processCheckBo: {
              orderCheckPeopleInfoList: newArray, // 直接作为顶层属性
              copyFor: userCcIds, // 直接作为顶层属性
              checkType: processCheckBo.checkType,
            },
          };
        } else {
          if (processCheckBo.checkPeopleIds) {
            userIds = processCheckBo.checkPeopleIds.map((item) =>
              item.userId ? Number(item?.userId) : item
            );
          }
          requestPayload = {
            ...form,
            createContract: createContract.value,
            endContract: endContract.value,
            processCheckBo: {
              checkPeopleIds: userIds, // 设置新的 checkPeopleIds 属性值
              copyFor: userCcIds,
              checkType: processCheckBo.checkType,
            },
          };
        }
        const response = await addconversionApi(requestPayload);

        if (response.code === 200) {
          // 添加成功的提示
          ElMessage.success(response.msg);
          // 跳转到列表
          router.push({
            path: "/project/Zhuanhua",
          });
        } else {
          ElMessage.error(response.msg);
        }
      } else if (route.query.name === "2") {
        let id = route.query.planId;
        let newArray = [];
        let userCcIds;
        let userIds;
        let requestPayload;

        if (processCheckBo.copyFor) {
          userCcIds = processCheckBo.copyFor.map((item) =>
            item.userId ? Number(item?.userId) : item
          );
        }
        if (processCheckBo.checkType === 1) {
          // 逐级审批 orderCheckPeopleInfoList
          // 使用 map 方法重构数组
          newArray = processCheckBo.checkPeopleIds.map((item, index) => {
            return {
              orderNum: index + 1,
              userId: item.userId ? Number(item?.userId) : item,
            };
          });
          requestPayload = {
            ...form,
            createContract: createContract.value,
            endContract: endContract.value,
            processCheckBo: {
              orderCheckPeopleInfoList: newArray, // 直接作为顶层属性
              copyFor: userCcIds, // 直接作为顶层属性
              checkType: processCheckBo.checkType,
            },
            planId: Number(id),
          };
        } else {
          // 编辑默认回显的时候 审批人
          if (processCheckBo.checkPeopleIds) {
            userIds = processCheckBo.checkPeopleIds.map((item) =>
              item.userId ? Number(item?.userId) : item
            );
          }
          requestPayload = {
            ...form,
            createContract: createContract.value,
            endContract: endContract.value,
            processCheckBo: {
              checkPeopleIds: userIds, // 设置新的 checkPeopleIds 属性值
              copyFor: userCcIds,
              checkType: processCheckBo.checkType,
            },
            planId: Number(id),
          };
        }
        const response = await updateApi(requestPayload);

        if (response.code === 200) {
          // 添加成功的提示
          ElMessage.success(response.msg);
          // 跳转到列表
          router.push({
            path: "/project/Zhuanhua",
          });
        } else {
          ElMessage.error(response.msg);
        }
      } else {
        if (route.query.show) {
          // 转立项审批
          let data = {
            checkOpinion: form.approvalOpinions,
            id: form.processCheckHistoryId,
            copyFor: processCheckBo.copyFor.map((item) => item.userId),
            keepCheckId: processCheckBo.checkPeopleIds.map(
              (item) => item.userId
            ),
            state: "1",
            fileList: form.approvalFile,
            keepCheck: form.keepCheck,
          };
          const res = await approvalTransfer(data);
          if (res.code === 200) {
            ElMessage.success("审批通过");
            router.push({
              path: "/examine",
            });
          }
        } else {
          // 项目信息审批
          let data = {
            checkOpinion: form.approvalOpinions,
            id: form.processCheckHistoryId,
            copyFor: processCheckBo.copyFor.map((item) => item.userId),
            keepCheckId: processCheckBo.checkPeopleIds.map(
              (item) => item.userId
            ),
            state: "1",
            fileList: form.approvalFile,
            keepCheck: form.keepCheck,
          };
          const res = await informationApprove(data);
          if (res.code === 200) {
            ElMessage.success("审批通过");
            router.push({
              path: "/examine",
            });
          }
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 取消
const resetForm = async (formEl) => {
  if (route.query.name === "6") {
    if (route.query.show) {
      // 转立项审批
      let data = {
        checkOpinion: form.approvalOpinions,
        id: form.processCheckHistoryId,
        copyFor: processCheckBo.copyFor.map((item) => item.userId),
        keepCheckId: processCheckBo.checkPeopleIds.map((item) => item.userId),
        state: "0",
        fileList: form.approvalFile,
        keepCheck: form.keepCheck,
      };
      const res = await approvalTransfer(data);
      if (res.code === 200) {
        ElMessage.success("审批已驳回");
        router.go(-1);
      }
    } else {
      let data = {
        checkOpinion: form.approvalOpinions,
        id: form.processCheckHistoryId,
        copyFor: processCheckBo.copyFor.map((item) => item.userId),
        keepCheckId: processCheckBo.checkPeopleIds.map((item) => item.userId),
        state: "0",
        fileList: form.approvalFile,
        keepCheck: form.keepCheck,
      };
      const res = await informationApprove(data);
      if (res.code === 200) {
        ElMessage.success("审批已驳回");
        router.go(-1);
      }
    }
  } else {
    if (!formEl) return;
    formEl.resetFields();
    router.push({
      path: "/project/Zhuanhua",
    });
  }
};
// 转立项回显
const handelApprovalQuery = async () => {
  let params = {
    id: Number(route.query.id),
  };
  const response = await approvalQueryApi(params);
  if (response.code === 200 && response.data) {
    for (let key in form) {
      if (response.data[key]) {
        form[key] = response.data[key];
      }
    }

    form.planName = response.data.projectName;
    form.planEncode = response.data.projectId;
    form.enterpriseContact = response.data.enterprisePerson;
    form.contactPhone = response.data.enterprisePhone;

    // 转化为数字类型
    form.tenderProject = Number(response.data.tenderProject);
    form.secrecyAgreement = Number(response.data.secrecyAgreement);

    // 转换成数组
    form.addressList = JSON.parse(response.data.address);
    //对业务类型进行判断处理，来决定使用哪个上传文件组件
    form.businessTypeList = response.data.test;
    ist.value = showFileUpload(response.data.test);

    // 行业
    form.industrys = JSON.parse(response.data.industry);
    
    // 文件转换
    form.planscFileList = response.data.contractFileList;

    form.projectFileList = response.data.projectFileList;

    // 合同工期
    datetime.value = [
      response.data.contractDuration,
      response.data.contractTermination,
    ];

    // 审批流程-审批
    // form.processCheckBo.checkPeopleIds = response.data.dataCheckInfo.checkList;

    // 审批人-抄送
    // form.processCheckBo.copyFor = response.data.dataCheckInfo.copyForList;

    // 审批进度列表
    activities.value = response.data.dataCheckInfo.opinons;
    //  审批id
    form.processCheckHistoryId =
      response.data.dataCheckInfo.processCheckHistoryId;

        // 审批方式
    processCheckBo.checkType =
      response.data &&
      response.data.dataCheckInfo &&
      response.data.dataCheckInfo.checkType;
    form.approvaDepts = JSON.parse(response.data.approvalDept);
    form.superviseDepts = JSON.parse(response.data.superviseDept);

    if (route.query.name === "5") {
      // 审批意见
      form.approvalOpinions =
        response.data &&
        response.data.dataCheckInfo &&
        response.data.dataCheckInfo.myCheckOpinionBo &&
        response.data.dataCheckInfo.myCheckOpinionBo.opinion;
      // 审批附件
      form.approvalFile =
        response.data &&
        response.data.dataCheckInfo &&
        response.data.dataCheckInfo.myCheckOpinionBo &&
        response.data.dataCheckInfo.myCheckOpinionBo.fileList;
      // 审批决定
      form.keepCheck =
        response.data &&
        response.data.dataCheckInfo &&
        response.data.dataCheckInfo.myCheckOpinionBo &&
        response.data.dataCheckInfo.myCheckOpinionBo.keepCheck;
    }
  }
};


let businessTypeDicData = [];
//获取
const getbusinessTypeDicData = async() => {
  //类型1为'a-j',类型2为'册'
  //返回值示例：
  // [
  //   {
  //       "type": "6,89",
  //       "value": 1
  //   },
  //   {
  //       "type": "[6,88],[6,90]",
  //       "value": 2
  //   }
  // ]
  let response = await getbusinessTypeDic();
  if (response.code === 200 && response.rows.length > 0) {
    businessTypeDicData = response.rows;
  } else {
    console.log(err);
  }

}

onMounted(async () => {
  hasButton();
  //需要查询：需要文件分类的业务类型的数据
  await getbusinessTypeDicData();
  form.units = unitsList[0].label;
  await handelIndustry();

  await businessTypeOptions();
  await handelLocation();

  if (
    (route.query.id && route.query.show) ||
    (route.query.name === "5" && route.query.shows)
  ) {
    await handelApprovalQuery();
  }
  
  

  //编辑 详情(分为转立项以及项目信息) 转立项  项目信息待我审批 项目信息我提交的 项目信息我已审批
  if (
    route.query.name === "2" ||
    (route.query.name === "3" && route.query.showDetails === "2") ||
    (route.query.name === "6" && route.query.info) ||
    (route.query.name === "5" && route.query.info)
  ) {
    await detailList();
  }

  if (route.query.name === "1") {
    form.projectUserDtoList.push(childRef.value.currentPerson);
  }
});
</script>
<style>
.el-dialog {
  background: #fff;
}
/**
   * form表单输入组件宽度
   **/

.el-select {
  width: 100%;
}

.el-input {
  width: 100%;
}

.el-cascader {
  width: 100%;
}

/* .el-date-editor {
  width: 100%;
} */

.el-input-number {
  width: 100%;
}
</style>

<style lang="scss" scoped>
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 10px;
}
h3 {
  border-bottom: 1px solid #e9e9eb;
  padding: 0 0 10px;
}
.require::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.table_container {
  margin: 10px 0;
}
.form-single-info {
  display: flex;
  justify-content: center;
}
.el-form-info {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}
.el-form-info strong {
  margin: 0 10px;
}
.el-form-info .el-time-picker {
  width: 100%;
}
.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  h5 {
    font-weight: bold;
  }
}
.Taskslist {
  box-shadow: 0px 0px 7px 0px rgba(77, 165, 255, 0.3);
  border-radius: 0px 0px 4px 4px;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 10px 0;
  h4 {
    padding: 0;
    margin: 10px 0;
    font-weight: bold;
  }
  span {
    display: block;
    color: #409eff;
    margin: 10px 0;
  }
  .color-text1 {
    color: #f56c6c;
  }
  .color-text2 {
    color: #c0c4cc;
  }
  .listimg {
    width: 60px;
    height: 60px;
    border-radius: 100%;
    overflow: hidden;
  }
  .listimg .el-image {
    width: 100%;
    height: 100%;
  }
}
</style>
